<?php

namespace Kordar\Excel;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use yii\base\Behavior;
use yii\base\InvalidConfigException;

class DataListExcelOutputBehavior extends Behavior
{
    const EVENT_OUTPUT_EXCEL = 'event-output-excel';

    /**
     * @var string
     */
    public $filename = 'output.xlsx';

    /**
     * @var null
     */
    public $template = null;

    public function outputExcel(OutputExcelInterface $event)
    {
        $spreadsheet = $this->spreadSheetHandle();

        $sheet = $spreadsheet->getActiveSheet();
        if (!$event instanceof OutputExcelInterface) {
            throw new InvalidConfigException('event 处理逻辑必须实现 OutputExcelInterface 接口！');
        }

        $event->render($sheet);
        $filename = $event->filename($this->filename);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
        header('Content-Disposition: attachment;filename="' . $filename . '"');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }

    public function events()
    {
        return [
            self::EVENT_OUTPUT_EXCEL => 'outputExcel'
        ];
    }

    /**
     * @return Spreadsheet
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    protected function spreadSheetHandle()
    {
        if ($this->template) {
            return \PhpOffice\PhpSpreadsheet\IOFactory::load($this->template);
        }
        return new Spreadsheet();
    }
}